<?php
/**
 * 微信用户信息服务
 * User: yyxi@vip.deyi.com
 * Date: 2018/01/09
 * Time: 11:47
 */

namespace Apps\Weixin\Services;

use Apps\Common\Constant\CacheKeyConstant;
use Apps\Common\Constant\CacheTimeoutConstant;
use Apps\Weixin\Models\WxUserInfo;
use Deyi\Functions\CacheFunction;
use Deyi\Functions\ObjectFunction;

class WxUserInfoService extends WxUserInfo
{

    public function getOneByOpenIdAndAppId($appId, $openId)
    {
        $cacheKey = CacheFunction::generateKey(CacheKeyConstant::WEIXIN_USERINFO_CACHE_KEY, $appId, $openId);

        $res = static::$_memcached->get($cacheKey);

        if (is_array($res)) {
            return $res;
        }

        $res = $this->getOneByFields(['appid' => $appId, 'openid' => $openId], true);

        if ($res) {
            $res = ObjectFunction::toAo($res);
            static::$_memcached->set($cacheKey, $res, CacheTimeoutConstant::LOCAL_HOUR_CACHE);
        }

        return $res;
    }

    public function getUserInfoCache($id)
    {

        $cacheKey = CacheFunction::generateKey(CacheKeyConstant::WEIXIN_USERINFO_BY_ID_CACHE_KEY, $id);

        $res = static::$_memcached->get($cacheKey);

        if (is_array($res)) {
            return $res;
        }

        $res = $this->getOneByField('id', $id);

        if ($res) {
            $res = ObjectFunction::toAo($res);;
            static::$_memcached->set($cacheKey, $res, CacheTimeoutConstant::LOCAL_HOUR_CACHE);
        }

        return $res;
    }
}